/**
 * 通用 2017-02-23 Juliana
 */


;(function (W, U) {
        "use strict";
        W.serverUrl = '/web';
        // UTF8字符集实际长度计算
        String.prototype.utf8Length = function () {
            var len = 0;
            for (var i = 0; i < this.length; i++) {
                if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) {
                    len += 3;
                } else {
                    len++;
                }
            }
            return len;
        }
        W.txz = {
            CONSTANT: {
                serverUrl: '/web',
                qrheadUrl: '/upload',
                loginUrl: '/web/pLogin.do',
            },
            saveStatus: true,//用于设置表单保存状态
            addToTopScroll: function () {
                var n = $('#top_back');
                $(window).scroll(function () {
                    $(window).scrollTop() > 700 ? n.css('display', 'block') : n.css('display', 'none');
                })
                $('.index-outside>section').scroll(function () {
                    $('.index-outside>section').scrollTop() > 700 ? n.css('display', 'block') : n.css('display', 'none');
                })

                n.click(function () {
                    $("html,body").animate({scrollTop: 0});
                    $(".index-outside>section").animate({scrollTop: 0});
                })
            },
            ajaxRequest: function (opts) {
                var that = this;
                opts = $.extend({
                    method: 'post',
                    params: {},
                    cacheObj: null,//定时缓存对象
                    cacheKey: '',//缓存key
                    callBack: function () {
                    }
                }, opts);
                $.ajax({
                    type: opts.method,
                    url: opts.url,
                    data: opts.params,
                    dataType: 'json',
                    context: $('body'),
                    success: function (data) {
                        if (opts.cacheObj) {
                            opts.cacheObj.removeCache();
                        }
                        typeof opts.callBack === 'function' && opts.callBack(data);
                    },
                    error: function (xhr, type) {
                        //用户登录状态失效
                        if (xhr.status == 401) {
                            location.href = that.CONSTANT.loginUrl;
                        } else {
                            typeof opts.callBack === 'function' && opts.callBack({
                                xhr: xhr
                            });
                        }
                    }
                })
            },
            openHelpDialog: function (opts) {
                var that = this;
                opts = $.extend({
                    title: '',
                    describe: '',
                    detailList: [],
                    theme: 'dialog-style-1',
                    id: 'help_dialog',
                    cb: function () {
                    }
                }, opts);
                var $dialog = that.openFDialog(opts), $content = $dialog.find('.content'), detailText = [];
                if (opts.detailList.length > 0) {
                    for (var i = 0; i < opts.detailList.length; i++) {
                        var detail = opts.detailList[i];
                        detailText.push(['<div class="inner-item">',
                            '<img src="' + detail.url + '" class="dialog-img" alt="">',
                            '<p class="inner-text">' + detail.text + '</p>',
                            '</div>'].join(''));
                    }
                }
                $content.append(detailText.join(''));
            },
            openQrDialog: function (opts) {
                var that = this;
                opts = $.extend({
                    title: '',
                    describe: '',
                    detailList: [],
                    id: 'qr_dialog',
                    cb: function () {
                    }
                }, opts);
                var $dialog = that.openFDialog(opts), $content = $dialog.find('.content'), detailText = [];
                if (opts.detailList.length > 0) {
                    for (var i = 0; i < opts.detailList.length; i++) {
                        var detail = opts.detailList[i];
                        detailText.push(['<div>',
                            '<div class="f18 ' + (detail.title ? '' : 'dn') + '">' + detail.title + '</div>',
                            '<img class="download-img" src="' + detail.url + '"/>',
                            '<a class="download-qrcode db" href="javascript:void(0);" data-url="' + detail.url + '">下载二维码</a>',
                            '<a class="look-url ' + (detail.link ? 'db' : 'dn') + '" href="javascript:void(0);" data-link="' + detail.link + '">查看链接</a>',
                            '</div>'].join(''));
                    }
                }
                $content.append(detailText.join(''));
                $dialog.find('.download-qrcode').click(function () {
                    window.location.href = txz.CONSTANT.serverUrl + "/fileupload/downloadNetwork.do?imgUrl=" + $(this).data('url');
                });
                $dialog.find('.look-url').click(function () {
                    var link = $(this).data('link');
                    layui.use(['layer'], function () {
                        var layer = layui.layer;
                        layer.msg(link, {time: 0, shade: .5, shadeClose: true});
                    });
                });

            },
            openFDialog: function (opts) {
                var that = this;
                opts = $.extend({
                    title: '',
                    describe: '',
                    theme: 'def-dialog',
                    detailList: [],
                    id: '',
                    cb: function () {
                    }
                }, opts);
                var $dialog = $('body', window.parent.parent.document).find('#' + opts.id);
                if ($dialog.length === 0) {
                    $('body', window.parent.parent.document).append([
                        '<div class="f-def-dialog ' + opts.theme + '" id="' + opts.id + '">',
                        '<div class="f-dialog-shadow"></div>',
                        '<div class="f-dialog-content">',
                        '<div class="dialog-header">',
                        '<div class="title"><span>' + (opts.title ? opts.title : '') + '</span></div>',
                        '<span class="close-icon"><i class="iconfont icon-close"></i></span>',
                        '</div>',
                        '<div class="dialog-detail">',
                        '</div>',
                        '</div>',
                        '</div>'].join(''));
                    $dialog = $('body', window.parent.parent.document).find('#' + opts.id);
                }
                var $detail = $dialog.find('.dialog-detail');
                $detail.html('');
                var detailText = [];
                if (opts.describe) {
                    detailText.push('<div class="detail-text">' + opts.describe + '</div>');
                }
                detailText.push('<div class="content"></div>');
                $detail.html(detailText.join(''));
                $dialog.find('.f-dialog-shadow,.close-icon,.close-btn').click(function () {
                    $dialog.fadeOut();
                });
                $dialog.fadeIn();
                return $dialog;
            },
            openQTip: function (el, title) {
                var index = null;
                layui.use(['layer'], function () {
                    var layer = layui.layer;
                    index = layer.tips(title || $(el).prop('title'), el, {
                        tips: [1, '#f4615c'],
                        time: 0
                    });
                });
                return index;
            },
            /**
             * 打开链接的窗口
             * @param opt
             */
            openDialogIframe: function (opt) {
                layui.use(['layer'], function () {
                    var layer = layui.layer;
                    var defOpt = {
                        name: 'layer',
                        url: '',
                        title: '标题',
                        width: '500',
                        height: '500',
                        target: '_parent',
                        btn: ['确定', '关闭'],
                        cb: function (opts) {
                            layer.close(opts.index);
                        }
                    };
                    defOpt = $.extend(defOpt, opt);
                    layer.open({
                        type: 2,
                        area: [defOpt.width, defOpt.height],
                        title: defOpt.title,
                        maxmin: true, //开启最大化最小化按钮
                        content: defOpt.url,
                        btn: defOpt.btn,
                        yes: function (index, layero) {
                            var body = layer.getChildFrame('body', index);
                            var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            var inputForm = body.find('#inputForm');
                            inputForm.attr("target", defOpt.target);//表单提交成功后，从服务器返回的url在当前tab中展示
                            typeof defOpt.cb === 'function' && defOpt.cb({
                                index: index,
                                layero: layero,
                                content: iframeWin.contentWindow
                            });
                        },
                        cancel: function (index) {
                        }
                    });
                });
            },
            /**初始化头部导航**/
            initHeader: function (opts) {
                var that = this;
                opts = $.extend({
                    nav: [],
                    info: '',
                    btns: ''
                }, opts);
                var $section = $('.section-main');
                $section.prepend(' <div class="c-def-header">' +
                    '                <div class="header-r-btns"></div>\n' +
                    '                <div class="header-l">\n' +
                    '                    <div class="header-nav">\n' +
                    '                        <span class="breadcrumb">\n' +
                    '                        </span>\n' +
                    '                    </div>\n' +
                    '                    <div class="header-info"></div>\n' +
                    '                </div>\n' +
                    '            </div>');
                var $crumb = $section.find('.breadcrumb'), $btns = $section.find('.header-r-btns'),
                    $info = $section.find('.header-info');
                var curIndex = 0;
                if (opts.nav.length) {
                    var crumbStrA = [];
                    for (var i = 0; i < opts.nav.length; i++) {
                        var nav = opts.nav[i];
                        crumbStrA.push('<a title="' + nav.name + '"' + (nav.href ? 'href="' + nav.href + '"' : '') + '>');
                        if (nav.curr || opts.nav.length === 1) {
                            crumbStrA.push('<cite>');
                        }
                        crumbStrA.push(nav.name);
                        if (nav.curr || opts.nav.length === 1) {
                            curIndex = i;
                            crumbStrA.push('</cite>');
                        }
                        crumbStrA.push('</a>');
                        if (i !== opts.nav.length - 1) {
                            crumbStrA.push('<span separator>/</span>');
                        }
                    }
                    $crumb.append(crumbStrA.join(''));
                }
                $info.append(opts.info);
                var btnStrA = [];
                if (opts.btns.length) {
                    for (var i = 0; i < opts.btns.length; i++) {
                        var btn = opts.btns[i], str = '', iconStr = '';
                        if (btn.type && btn.type === 'back') {
                            str = '<a href="javascript:window.history.back()" class="layui-btn layui-btn-radius layui-btn-danger"><i class="iconfont icon-back btn-icon"></i>返回 </a>';
                        } else {
                            if (btn.isCheckExpire) {
                                str += '<a href="javascript:txz.expireCheck(\'' + btn.href + '\')" class="layui-btn layui-btn-radius layui-btn-danger">_ICON' + btn.name + ' </a>';
                            } else {
                                str += '<a href="' + btn.href + '" class="layui-btn layui-btn-radius layui-btn-danger">_ICON' + btn.name + ' </a>';
                            }
                            if (btn.icon) {
                                iconStr = '<i class="iconfont icon-' + btn.icon + ' btn-icon"></i>';
                            }
                            str = str.replace('_ICON', iconStr);
                        }
                        btnStrA.push(str);
                    }
                    $btns.append(btnStrA.join(''));
                }
            },
            /**
             * 普通滑动到底部监听
             * @param cb 回调
             * @param h 距离底部高度为h时触发回调
             * @param o 监听的对象，默认为window
             */
            toBtmListener: function (cb, h, o) {
                var params = {
                    h: h || 20
                }
                o = o || window;

                function callback() {
                    var scrollTop = $(o).scrollTop();
                    var scrollHeight = $(document).height();
                    var windowHeight = $(o).height();
                    if (scrollTop + windowHeight >= scrollHeight - params.h) {
                        typeof cb === "function" && cb();
                    }
                }

                var scrollTimer = null;
                $(o).scroll(function () {
                    if (scrollTimer) {
                        clearTimeout(scrollTimer)
                    }
                    scrollTimer = setTimeout(function () {
                        callback()
                    }, 400);
                });
            },
            errImg: function (o) {
                o.src = window.serverUrl + '/image/404.png';
            },
            imgLoad: function (o) {
                var parent = o.parentNode, pW = parent.clientWidth, pH = parent.clientHeight;
                var wRatio = o.clientWidth / pW, hRatio = o.clientHeight / pH;
                if (wRatio > hRatio) {
                    o.style.width = 'auto';
                    o.style.height = '100%';
                } else {
                    o.style.width = '100%';
                    o.style.height = 'auto';
                }
            },
            /**
             * 打开选择图片
             * @param opts
             */
            openSelImg: function (opts) {
                var that = this, $body = $('html,body'), scrollTop = $(window).scrollTop();
                opts = $.extend({
                    min: 1, // 最小选择数
                    max: 1000,// 最大选择数
                    type: '', // 业务类型
                    compress: 1, // 是否需要压缩
                    cb: function () {
                    }
                }, opts);
                var url = txz.CONSTANT.serverUrl + '/file/img/selImg.do?compress=' + opts.compress + '&min=' + opts.min + '&max=' + opts.max + '&type=' + opts.type;
                if (opts.info) {
                    url += '&info=' + opts.info;
                }
                layer.open({
                    type: 2,
                    area: ['800px', '600px'],
                    title: '选择图片',
                    content: url,
                    btn: ['确定', '关闭'],
                    yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = layero.find('iframe')[0];
                        if (iframeWin.contentWindow.validate()) {
                            var succFiles = iframeWin.contentWindow.getImgs();
                            typeof opts.cb === 'function' && opts.cb(succFiles);
                            iframeWin.contentWindow.close();
                        }
                    },
                    cancel: function (index) {
                    },
                    end: function () {
                        typeof opts.closeCb === 'function' && opts.closeCb();
                    }
                });
            },
            /**
             * 打开选择视频
             * @param opts
             */
            openSelVideo: function (opts) {
                var that = this, $body = $('html,body'), scrollTop = $(window).scrollTop();
                opts = $.extend({
                    min: 1, // 最小选择数
                    max: 10,// 最大选择数
                    type: '', // 业务类型
                    backVideoOrIframe: 'iframe',
                    cb: function () {
                    }
                }, opts);
                var url = txz.CONSTANT.serverUrl + '/file/video/selVideo.do?min=' + opts.min + '&max=' + opts.max + '&type=' + opts.type + '&backType=' + opts.backVideoOrIframe;
                if (opts.info) {
                    url += '&info=' + opts.info;
                }
                layer.open({
                    type: 2,
                    area: ['800px', '600px'],
                    title: '选择视频',
                    content: url,
                    btn: ['确定', '关闭'],
                    yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = layero.find('iframe')[0];
                        if (iframeWin.contentWindow.validate()) {
                            var succFiles = iframeWin.contentWindow.getImgs();
                            typeof opts.cb === 'function' && opts.cb(succFiles);
                            iframeWin.contentWindow.close();
                        }
                    },
                    cancel: function (index) {
                    },
                    end: function () {
                        typeof opts.closeCb === 'function' && opts.closeCb();
                    }
                });
            },
            openPhotoUpload: function (opts) {
                var url = txz.CONSTANT.serverUrl + '/file/img/photo/uploadImg.do?compress=1&id=' + opts.id + '&tagId=' + opts.tagId;
                layer.open({
                    type: 2,
                    area: ['800px', '600px'],
                    title: '上传图片',
                    content: url,
                    btn: ['上传'],
                    yes: function (index, layero) {
                        var iframeWin = layero.find('iframe')[0];
                        iframeWin.contentWindow.upload();
                    },
                    cancel: function (index, layero) {
                        var iframeWin = layero.find('iframe')[0];
                        iframeWin.contentWindow.close();
                    },
                    end: function () {
                        typeof opts.closeCb === 'function' && opts.closeCb();
                    }
                });
            },
            openThirdPhotoUpload: function (opts) {
                var url = txz.CONSTANT.serverUrl + '/photo/album/third/photo/uploadImg.do?compress=1&id=' + opts.id + '&tagId=' + opts.tagId;
                layer.open({
                    type: 2,
                    area: ['800px', '600px'],
                    title: '上传图片',
                    content: url,
                    btn: ['上传'],
                    yes: function (index, layero) {
                        var iframeWin = layero.find('iframe')[0];
                        iframeWin.contentWindow.upload();
                    },
                    cancel: function (index, layero) {
                        var iframeWin = layero.find('iframe')[0];
                        iframeWin.contentWindow.close();
                    },
                    end: function () {
                        typeof opts.closeCb === 'function' && opts.closeCb();
                    }
                });
            },
            /**
             * 删除
             *
             * @param content
             *            弹窗内容
             * @param url
             *            请求
             * @param tip
             *            提示语
             */
            deleteObject: function (content, url, tip, myForm) {
                top.layer.confirm(content, {
                    icon: 3,
                    title: '系统提示'
                }, function (index) {
                    top.layer.close(index);
                    //loading层
                    var loadIndex = layer.load(1, {
                        shade: [0.1, '#fff'] //0.1透明度的白色背景
                    });
                    $.post(url, {}, function (data) {
                        top.layer.close(loadIndex);
                        if (data.success) {
                            util.layerMsgSuccess("删除成功", function () {
                                if (util.isValid(myForm)) {
                                    submitFunction(myForm);
                                } else {
                                    window.location.reload();
                                }
                            })
                        } else {
                            util.layerMsgError(tip || data.description || '删除失败');
                        }
                    });
                });
            },
            /**
             * layer的submit事件
             * @param elemt 提交按钮
             * @param callBack 回调函数
             */
            submitObject: function (elemt, callBack, checkId) {
                //loading层
                var loadIndex = top.layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });
                $(elemt).removeAttr("lay-submit");

                if (checkId == '') {
                    txz.expireCheck('', function () {
                        typeof callBack === 'function' && callBack(function () {
                            top.layer.close(loadIndex);
                            setTimeout(function () {
                                $(elemt).attr("lay-submit", "");
                            }, 1000);
                        });
                    }, function () {
                        top.layer.close(loadIndex);
                        setTimeout(function () {
                            $(elemt).attr("lay-submit", "");
                        }, 1000);
                    });
                } else {
                    typeof callBack === 'function' && callBack(function () {
                        top.layer.close(loadIndex);
                        setTimeout(function () {
                            $(elemt).attr("lay-submit", "");
                        }, 1000);
                    });
                }
            },
            addAutocomplete: function () {
                $("[name='createStart']").prop('autocomplete', 'off');
                $("[name='createEnd']").prop('autocomplete', 'off');
            },
            openExpireDialog: function (opts) {
                var that = this;
                opts = $.extend({
                    title: '',
                    describe: '',
                    detailList: [],
                    id: 'expire_dialog',
                    cb: function () {
                    }
                }, opts);
                var $dialog = that.openFDialog(opts), $content = $dialog.find('.content'), detailText = [];
                var xfOpt = '<a href="' + txz.CONSTANT.serverUrl + '/serviceOrder/info.do" class="layui-btn layui-btn-danger" style="margin-left: 50px;">立即续费</a>';
                if (opts.isChild) {
                    xfOpt = ''
                }
                detailText.push(['<div>' +
                    '<div class="mb10"><i class="iconfont icon-info expire-tip-icon"></i><p class="expire-tip-text">提示</p></div>' +
                    '<div class="expire-tip-desc"><p>您的账户已经到期，续费即可继使用该功能，赶紧联系我们吧！</p><p>官方咨询电话：4008-771-663</p></div>' +
                    '<div>' +
                        '<a href="javascript:void(0)" class="layui-btn layui-btn-primary close-btn">&emsp;取消&emsp;</a>' +
                        xfOpt +
                    '</div>' +
                '</div>']);
                $content.append(detailText.join(''));

                $dialog.find('.f-dialog-shadow,.close-btn').click(function () {
                    $dialog.fadeOut();
                });

                $dialog.css('z-index', '1989102011');
            },
            expireCheck: function (href, fn, failFn) {
                console.log('expireCheck');
                layui.use(['layer'], function(){
                    layer = layui.layer;
                });
                $.get(txz.CONSTANT.serverUrl + "/system/member/expireCheck.do", {}, function (res) {
                    if (res.success) {
                        if (!res.data.isExpire) {
                            if (href) {
                                window.location.href = href;
                            } else if (fn) {
                                fn.apply();
                            }
                        } else {
                            if (failFn) {
                                failFn.apply();
                                txz.openExpireDialog({
                                    isChild: res.data.isChild
                                });
                            } else {
                                txz.openExpireDialog({
                                    isChild: res.data.isChild
                                });
                            }
                        }
                    } else {
                        if (href) {
                            window.location.href = href;
                        } else if (fn) {
                            fn.apply();
                        }
                    }
                })
            },
            /**
             * 验证手机号或用户名是否为唯一
             * @param key username/mobile
             * @param value username/mobile 值
             * @param userId 用户id
             * @param type 用户类型 1：个人 2：机构 3：平台
             * @param roleName 是否拥有这个角色
             * @returns {boolean}
             */
            checkIsUnique : function (key, value, userId, type, roleName) {
                var isRepeat = undefined;
                $.ajax({
                    type: 'POST',
                    async: false, // 使用同步的方法
                    data: {
                        value: value,
                        userId: userId,
                        key: key,
                        type: type,
                        roleName: roleName
                    },
                    dataType: 'json',
                    success: function (res) {
                        if (res.success) {
                            isRepeat = !res.data;
                        }
                    },
                    url: txz.CONSTANT.serverUrl + '/system/member/checkUniqueProperty.do'
                });
                return isRepeat;
            },
            /**
             * 验证手机号或用户名是否为唯一
             * @param key username/mobile
             * @param value username/mobile 值
             * @param userId 用户id
             * @param type 用户类型 1：个人 2：机构 3：平台
             * @param roleName 是否拥有这个角色
             * @returns {boolean}
             */
            checkGroupIsUnique : function (key, value, userId, type, roleName) {
                var isRepeat = undefined;
                $.ajax({
                    type: 'POST',
                    async: false, // 使用同步的方法
                    data: {
                        value: value,
                        userId: userId,
                        key: key,
                        type: type,
                        roleName: roleName
                    },
                    dataType: 'json',
                    success: function (res) {
                        if (res.success) {
                            isRepeat = !res.data;
                        }
                    },
                    url: txz.CONSTANT.serverUrl + '/member/group/checkUniqueProperty.do'
                });
                return isRepeat;
            }
        }
        W.txz.addAutocomplete();
    }
    (window, undefined)
)
;